/**
 * Created by wry on 2015/1/13.
 */

var activityService = require('../services/activityService');
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var questionService = require('../services/questionService');
var moment = require('moment');

exports.createActivity = function (req, res) {
    var input = req.body;
    var token = req.params.token;
    var bgNo = req.params.bgNo;
    var objectName = 'activity';
    activityService.createActivityService(input, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when create an activity...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when create an activity...!'));
        } else {
            toolUtil.uploadImageService(objectName, result._id, req, function (err, images) {
                var tempImages = new Array();
                var k = 0;
                for (i = 0; i < images.length; i++) {
                    if (images[i] != null) {
                        if (i == bgNo) {
                            tempImages[k++] = {
                                "imageURL": images[i],
                                "isBackgroundImage": true
                            }
                        } else {
                            tempImages[k++] = {
                                "imageURL": images[i]
                            }
                        }
                    }
                }
                activityService.setImagesToActivity(result._id, tempImages, function (err, result) {
                    if (err || tempImages == null) {
                        res.json(messageUtil.composeFailedMessage(req, 'Failed to upload question Images... - ' + err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });
            })
        }
    })
};

exports.updateActivity = function (req, res) {
    var input = req.body;
    var activityId = req.params.activityId;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            logger.error('updateActivity - uploadImage - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, '更新活动失败'));
        } else {
            var tempImages = [];
            var k = 0;
            for (var i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            input['images'] = tempImages;

            activityService.updateActivityService(activityId, input, function (err, result) {
                if (err) {
                    logger.error('Failed to updateActivity... - ' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null));

                    //截至日期放redis
                    if (input.deadline != null) {
                        var deadline = moment(input.deadline).toDate();
                        var key = 'activity:deadline';
                        redisClient.zadd(key, deadline.getTime() / 1000, activityId + '');
                    }
                }
            });
        }
    });
};

/**
 * 获取活动列表
 */
exports.getTopActivityList = function (req, res) {
    var token = req.params.token;
    activityService.getTopActivityListService(token, function (err, results) {
        if (err) {
            logger.error('Failed to get top activity list... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get top activity list... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results[0].concat(results[1])));
        }
    })
};

/**
 * 获取活动详情
 */
exports.getActivityDetail = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    activityService.getActivityDetailService(activityId, token, function (err, result) {
        if (err) {
            logger.error('Failed to get top activity detail... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get top activity detail... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 报名
 */
exports.doRegister = function (req, res) {
    var input = req.body;
    var token = req.params.token;

    activityService.doRegisterService(token, input, function (err, result) {
        if (err) {
            logger.error('Failed to register activity... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to register activity... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 发布动态
 */
exports.addActivityInformation = function (req, res) {
    var input = req.body;
    var token = req.params.token;
    var objectName = 'activity';

    toolUtil.uploadImageService(objectName, input.activityId, req, function (err, images) {
        var tempImages = new Array();
        var k = 0;
        for (i = 0; i < images.length; i++) {
            if (images[i] != null) {
                tempImages[k++] = {
                    "photoURL": images[i]
                }
            }
        }
        activityService.addActivityInformationService(tempImages, input, token, function (err, result) {
            if (err) {
                logger.error('Failed to add activity information... - ' + err.message);
                res.json(messageUtil.composeFailedMessage(req, 'Failed to add activity information... - ' + err.message));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            }
        })
    });
};

exports.getActivityPhotoDetail = function (req, res) {
    var activityId = req.params.activityId;
    var imageId = req.params.imageId;

    activityService.getActivityPhotoDetailService(activityId, imageId, function (err, result) {
        if (err) {
            logger.error('Failed to get activity photo detail... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get activity photo detail... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 评论图片
 */
exports.postPhotoComment = function (req, res) {
    var input = req.body;
    var token = req.params.token;

    activityService.postPhotoCommentService(input, token, function (err, result) {
        if (err) {
            logger.error('Failed to post photo comment... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to post photo comment... - ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 获取我的活动
 */
exports.getMyActivity = function (req, res) {
    var token = req.params.token;
    activityService.getMyActivityService(token, function (err, results) {
        if (err) {
            logger.error('Failed to get my activity... - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get my activity... - ' + err.message));
        } else {
            if (results != null) {
                var temp = new Array();
                results.forEach(function (result) {
                    if (result != null) {
                        result.forEach(function (t) {
                            temp.push(t);
                        })
                    }
                });
                temp.sort(function (a, b) {
                    return b.startDateTime - a.startDateTime;
                });

                //删除重复活动
                var newArray = [];
                var provisionalTable = {};
                for (var i = 0, item; temp[i] != null && (item = temp[i]._id) != null; i++) {
                    if (!provisionalTable[item]) {
                        newArray.push(temp[i]);
                        provisionalTable[item] = true;
                    }
                }
                temp = newArray;

                var weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

                temp.forEach(function (t) {
                    var start = moment(t.startDateTime).format('MM月DD日 HH:mm');
                    var end = moment(t.endDateTime).format('MM月DD日 HH:mm');
                    t._doc['weekDay'] = weekDay[moment(t.startDateTime).format('d')];
                    t._doc['month'] = moment(t.startDateTime).format('YYYY-MM');
                    t._doc['day'] = moment(t.startDateTime).format('D');
                    t._doc['time'] = start + '—' + end;

                    t.startDateTime = undefined;
                    t.endDateTime = undefined;
                })

            }
            res.json(messageUtil.composeSucceededMessage(req, null, temp));
        }
    })
};

/**
 * 获取报名列表
 * @param req
 * @param res
 */
exports.getActivityRegistrationList = function (req, res) {
    var activityId = req.params.activityId;

    activityService.getActivityRegistrationListService(activityId, function (err, results) {
        if (err) {
            logger.error('Failed to get activity registration list ' + err.message)
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get activity registration list ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 获取活动聊天室成员
 * @param req
 * @param res
 */
exports.getActivityGroupMember = function (req, res) {
    var groupId = req.params.groupId;

    activityService.getActivityGroupMemberService(groupId, function (err, results) {
        if (err) {
            logger.error('Failed to get activity group member ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get activity group member ' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.searchActivityVenueByKeyword = function (req, res) {
    var keyword = req.params.keyword;

    activityService.searchActivityVenueByKeywordService(keyword, function (err, results) {
        if (err) {
            logger.error('Failed to search activity venue ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to search activity venue' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 上传活动聊天文本信息
 * @param req
 * @param res
 */
exports.postTextMessage = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    activityService.postTextMessageService(token, input, function (err, result) {
        if (err) {
            logger.error('Failed to post activity group chat ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to post activity group chat' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getActivityChats = function (req, res) {
    var groupId = req.params.groupId;

    activityService.getActivityChatsService(groupId, function (err, results) {
        if (err) {
            logger.error('Failed to get activity chats' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Failed to get activity chats' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 创建邻里活动
 */
exports.postNeighbourActivity = function (req, res) {

    var input = req.body;
    var token = req.params.token;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            logger.error('postQuestionNew - uploadImage - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, '创建活动失败'));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (var i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            input['images'] = tempImages;

            activityService.postNeighbourActivityService(token, input, function (err, result) {
                if (err) {
                    logger.error('postQuestionNew - - ' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, '创建活动失败'));
                    toolUtil.deleteImage(images);
                } else {
                    var data = {
                        _id: result[0]._doc._id
                    };
                    toolUtil.hessianInvokeAddScore(token, 'postQuestion', function (score) {
                        if (score != null && score.currentValue != null) {
                            data.currentValue = score.currentValue;
                        }
                        res.json(messageUtil.composeSucceededMessage(req, null, data));
                    });

                    //截至日期放redis
                    if (input.deadline != null) {
                        var deadline = moment(input.deadline).toDate();
                        var key = 'activity:deadline';
                        redisClient.zadd(key, deadline.getTime() / 1000, data._id + '');
                    }
                }
            });
        }
    });
};

/**
 *  参加活动
 */
exports.joinInNeighbourActivity = function (req, res) {

    var token = req.params.token;
    var input = req.body;


    activityService.joinInNeighbourActivityService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when joinInNeighbourActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                number: result[3]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};


exports.joinInActivityNew = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    activityService.joinInActivityNewService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when joinInNeighbourActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result[3]));
        }
    });
};


exports.exitNeighbourActivity = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;

    activityService.exitNeighbourActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when exitNeighbourActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                number: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/**
 * 活动详情
 */
exports.getDetailOfActivity = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    var clickSource = req.cparams.clickSource;

    activityService.getDetailOfActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getDetailOfQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));

            if (clickSource != null) {
                var message = {
                    userId: token,
                    contentId: activityId,
                    type: 2,
                    clickSource: clickSource,
                    typeDesc: '邻里活动',
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
};

/**
 * 活动回复详情
 * @param req
 * @param res
 */
exports.getDetailReplyOfActivity = function (req, res) {
    var page = req.params.page;
    var token = req.params.token;
    var activityId = req.params.activityId;

    var vcode = req.cparams.vcode;

    activityService.getDetailReplyOfActivityService(token, activityId, page, vcode, function (err, result) {
        if (err) {
            logger.error('Exception happened when getDetailReplyOfActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};


/**
 * 获取活动参与者列表
 * @param req
 * @param res
 */
exports.getActivityPartakeList = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;
    var page = req.params.page;

    activityService.getActivityPartakeListService(token, activityId, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when getActivityPartakeList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getActivityPartakeListNew = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;
    var page = req.params.page;

    activityService.getActivityPartakeListNewService(token, activityId, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when getActivityPartakeList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.searchPartake = function (req, res) {
    var activityId = req.body.activityId;
    var keyword = req.body.keyword;

    activityService.searchPartakeService(keyword, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when searchPartake ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                keyword: keyword,
                partake: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
}


exports.deleteActivity = function (req, res) {
    var token = req.params.token;
    var activityId = req.params.activityId;

    activityService.deleteActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when deleteActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 活动评论
 * @param req
 * @param res
 */
exports.postActivityReply = function (req, res) {
    var input = req.body;
    var token = req.params.token;
    var activityId = req.params.activityId;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            logger.error('postQuestionNew - uploadImage - ' + err.message);
            res.json(messageUtil.composeFailedMessage(req, '回复失败'));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (var i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            input['images'] = tempImages;

            activityService.postActivityReplyService(token, activityId, input, function (err, result) {
                if (err) {
                    logger.error('Exception happened when postActivityReply ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message));
                } else {
                    var replyId = {
                        "_id": result[3].replies[result[3].replies.length - 1]._id
                    };
                    toolUtil.hessianInvokeAddScore(token, 'postReply', function (score) {
                        if (score != null && score.currentValue != null) {
                            replyId.currentValue = score.currentValue;
                        }
                        res.json(messageUtil.composeSucceededMessage(req, null, replyId));
                    });


                    if (input.uList != null && typeof input.uList == 'string') {
                        input.uList = [input.uList];
                    }


                    //推送
                    toolUtil.putMessageQAMQ({
                        msgType: 'reply',
                        isExistAt: input.uList != null && input.uList.length > 0 ? 1 : 0,
                        atUidList: input.uList,
                        replyUid: token,
                        topicId: result[3]._id + '',
                        replyId: replyId._id + '',
                        replyDesc: input.replyDesc,
                        contentType: 'activity',
                        isAsk: input.replyTo == null ? 0 : 1,
                        toReplyUid: input.replyTo
                    });


                    if (input.replyDesc != null && input.replyDesc != '') {
                        toolUtil.filteringSensitiveWords(result[3]._id, replyId._id, input.replyDesc, 'activity');
                    }

                    //@功能
                    if (input.uList != null && input.uList.length > 0 && input.replyDesc.indexOf(atFlag) != -1) {
                        questionService.replyAtService(result[3], replyId._id, input.uList, 'neighbourActivity', token, input.replyDesc);
                    }
                }
            })
        }
    });
};

exports.thankActivityReply = function (req, res) {
    var activityId = req.params.activityId;
    var replyId = req.params.replyId;
    var replyBy = req.params.replyBy;
    var token = req.params.token;

    activityService.thankActivityReplyService(activityId, replyId, replyBy, token, function (err, result) {
        if (err) {
            logger.error('thankActivityReply--' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, '感谢成功', null));
        }
    })
}

/**
 * 关闭活动
 * @param req
 * @param res
 */
exports.closeActivity = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;

    activityService.closeActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when closeActivity ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));

            var key = 'activity:deadline';
            redisClient.ZREM(key, activityId + '');
        }
    })
};

exports.setPartakeStatus = function (req, res) {
    var input = req.body;

    activityService.setPartakeStatusService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when setPartakeStatus ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.setPartakeManagerStatus = function (req, res) {
    var input = req.body;

    activityService.setPartakeManagerStatusService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when setPartakeManagerStatus ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 获取活动列表
 * @param req
 * @param res
 */
exports.getActivityList = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    var level;
    var noTag;
    if (req.cparams != null && req.cparams.level != null) {
        level = Number(req.cparams.level);
    }
    if (req.cparams != null && req.cparams.noTag != null) {
        noTag = Number(req.cparams.noTag);
    }

    activityService.getActivityListService(token, ts,level,noTag, function (err, result) {
        if (err) {
            logger.error('Exception happened when getActivityList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                //ts: result.length > (listPageSize - 1) ? (result[result.length - 1].dateCreated.getTime() - 1000) : (new Date("2000/04/01 00:00:00")).getTime(),
                ts: Number(ts) + 1,
                activityList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/**
 * 举报活动
 */
exports.reportActivity = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    activityService.reportActivityService(token, activityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to update the question data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, '举报成功，请等待审核', null));
        }
    })
};

exports.deleteActivityReply = function (req, res) {
    var activityId = req.params.activityId;
    var token = req.params.token;
    var replyId = req.params.replyId;

    activityService.deleteActivityReplyService(token, activityId, replyId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to deleteActivityReply' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getMyInvolvedActivity = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    activityService.getMyInvolvedActivityService(token, ts, function (err, result) {
        if (err) {
            logger.error('Exception happened when getActivityList ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err));
        } else {

            var ts = result.length > 0 ? result[result.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime();

            var data = {
                ts: ts,
                activityList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.getMyReleasedActivity = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    activityService.getMyReleasedActivityService(token, ts, function (err, result) {
        if (err) {
            logger.error('Exception happened when getMyReleasedActivityService ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err));
        } else {
            var ts = result.length > 0 ? result[result.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime();
            var data = {
                ts: ts,
                activityList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.pushActivityMessage = function (req, res) {
    var input = req.body;

    redisClient.get('activityid:' + input.activityId + ':pushcount', function (err, pushCount) {
        pushCount = pushCount ? Number(pushCount) : 0;
        if (pushCount < activityTotalPush) {
            var data = {
                msgContent: input.message,
                activityId: input.activityId
            };
            toolUtil.putMessageActivityMQ(data);
            var result = {
                pushCount: pushCount + 1,
                totalPushCount: activityTotalPush
            };
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        } else {
            res.json(messageUtil.composeErrorMessage(req, ErrorMessage.ACTIVITY_PUSH))
        }
    });
};
